package com.googlecode.wickedforms.xvergabe.xml;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlValidationError;
import org.xvergabe.xsd.forms.components.x20.FormDocument;
import org.xvergabe.xsd.forms.components.x20.FormDocument.Form;

/**
 * Reads XML from a given file.
 * 
 * @author hombergs
 * 
 */
public class FormXmlStreamReader implements FormXmlReader {

	private final InputStream inputStream;

	public FormXmlStreamReader(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	@Override
	public Form readFromXml() throws XmlException, IOException {
		FormDocument xmlFormDocument = FormDocument.Factory.parse(inputStream,
				new XmlOptions().setCharacterEncoding("UTF-8"));
		return xmlFormDocument.getForm();
	}

	@Override
	public List<String> validate() throws XmlException, IOException {
		List<XmlValidationError> validationErrors = new ArrayList<XmlValidationError>();
		XmlOptions options = new XmlOptions();
		options.setErrorListener(validationErrors);
		FormDocument xmlFormDocument = FormDocument.Factory.parse(inputStream);
		xmlFormDocument.validate(options);

		List<String> resultList = new ArrayList<String>();
		for (XmlValidationError error : validationErrors) {
			resultList.add(error.getMessage() + " (line " + error.getLine()
					+ ")");
		}

		System.out.println("Anzahl Validierungsfehler: " + resultList.size());

		return resultList;
	}

}
